//
//  String+Extension.swift
//  DoctorEPlus
//
//  Created by 王林波 on 2020/10/27.
//

import Foundation
import UIKit
extension String {
    func toHexColor(alpha: CGFloat) -> UIColor {
        var red: UInt32 = 0, green: UInt32 = 0, blue: UInt32 = 0
        var hex = self
        // 如果传入的十六进制颜色有前缀，去掉前缀
        if hex.hasPrefix("0x") || hex.hasPrefix("0X") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 2)...])
        } else if hex.hasPrefix("#") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 1)...])
        }
        // 如果传入的字符数量不足6位按照后边都为0处理，当然你也可以进行其它操作
        if hex.count < 6 {
            for _ in 0..<6-hex.count {
                hex += "0"
            }
        }
        // 分别进行转换
        // 红
        Scanner(string: String(hex[..<hex.index(hex.startIndex, offsetBy: 2)])).scanHexInt32(&red)
        // 绿
        Scanner(string: String(hex[hex.index(hex.startIndex, offsetBy: 2)..<hex.index(hex.startIndex, offsetBy: 4)])).scanHexInt32(&green)
        // 蓝
        Scanner(string: String(hex[hex.index(startIndex, offsetBy: 4)...])).scanHexInt32(&blue)

        return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
    }
    
    func findTextRange(text: String) -> NSRange{
        let rangeInStr = self.range(of: text)
        let utf16view = self.utf16
        if let from = rangeInStr?.lowerBound.samePosition(in: utf16view),
            let to = rangeInStr?.upperBound.samePosition(in: utf16view) {
            return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to))
        }
        return NSMakeRange(0, 0)
    }
    
    
    func calSizeOfText(font: UIFont, size: CGSize) -> CGSize {
        let attributes = [NSAttributedString.Key.font: font]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
            return rect.size;
    }
    
    
    static func isStrEmpty(aStr: String?) -> Bool {
        if aStr != nil {
            if aStr!.count > 0{
                return false
            }else {
                return true
            }
        }else {
            return true
        }
    }
    
    func toAttribute() -> NSMutableAttributedString {
        let att = NSMutableAttributedString.init(string: self)
        return att
    }
    
    static func getRecorderPath() -> String {
        var recorderPath:String? = nil
        let now:Date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yy-MMMM-dd"
        recorderPath = "\(NSHomeDirectory())/Documents/"
        
        dateFormatter.dateFormat = "yyyy-MM-dd-hh-mm-ss"
        recorderPath?.append("\(dateFormatter.string(from: now))-MySound.ilbc")
        return recorderPath!
    }
    
    public func py() -> String {
        let mutableString = NSMutableString(string: self)
        //把汉字转为拼音
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        //去掉拼音的音标
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let py = String(mutableString)
        return py
    }
    
    public func firstCharacter() -> String {
        let firstCharacter = String(describing: self.first!)
        if firstCharacter.isLetterOrNum() {
            return firstCharacter.uppercased()
        }
        let py = String(describing: firstCharacter.py().first!)
        return py.uppercased()
    }
    
    public func isLetterOrNum() -> Bool {
        if let value = UnicodeScalar(self)?.value {
            if value >= 65 && value <= 90 {
                return true
            }
        }
        return false
    }
    
    
    public func removeAllBlank() -> String {
        var newString: String = self
        newString = newString.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
        newString = newString.replacingOccurrences(of: "\n", with: "")
        newString = newString.replacingOccurrences(of: "\r", with: "")
        newString = newString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        
        return newString
    }
    
    
 
    static var today: String {
        get {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            return dateFormatter.string(from: Date())
        }
    }
}





// 富文本和计算
extension NSMutableAttributedString {
    func addLineSpace(_ space: CGFloat) -> Self {
        let style = NSMutableParagraphStyle.init()
        style.lineSpacing = space
        style.lineBreakMode = .byTruncatingTail
        self.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSMakeRange(0, self.length))
        return self
    }
    
    func addTextAlignmet(_ alignmet: NSTextAlignment) {
        let style = NSMutableParagraphStyle.init()
        style.alignment = alignmet
        style.lineBreakMode = .byTruncatingTail
        self.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSMakeRange(0, self.length))
    }
    
    func addFont(_ font: UIFont) {
        self.addAttribute(NSAttributedString.Key.font, value: font, range: NSMakeRange(0, self.length))
    }
    
    func addAllTextColor(_ color: UIColor) {
        self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSMakeRange(0, self.length))
    }
    
    func addSpecialTextColor(_ text: String, _ color: UIColor) {
        let range = self.string.findTextRange(text: text)
        if range.length != 0 {
            self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        }
    }
    
    func addSpecialFont(_ text: String, _ font: UIFont) {
        let range = self.string.findTextRange(text: text)
        if range.length != 0 {
            self.addAttribute(NSAttributedString.Key.font, value: font, range: range)
        }
    }
    
    func calculateSize(_ maxSize: CGSize) -> CGSize {
        let label = UILabel.init(frame: CGRect(x: 0, y: 0, width: maxSize.width, height: maxSize.height))
        label.numberOfLines = 0
        label.attributedText = self
        label.sizeToFit()
        return label.frame.size
    }
}


extension NSAttributedString {
    func sizeAttribute(_ maxSize: CGSize) -> CGSize {
        let label = UILabel.init(frame: CGRect(x: 0, y: 0, width: maxSize.width, height: maxSize.height))
        label.numberOfLines = 0
        label.attributedText = self
        label.sizeToFit()
        return label.frame.size
    }
}


// 转换
// json转字典
extension String {
    func transJsonToDic() -> [String: Any] {
        let jsonData:Data = self.data(using: .utf8)!
        
           let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
           if dict != nil {
            return dict as! [String: Any]
           }
        return [:]
    }
    
    
    func transJsonToArray() -> NSArray {
        let jsonData:Data = self.data(using: .utf8)!
                 
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
            if array != nil {
                return array as! NSArray
        }
        return array as! NSArray
    }
}


// 默认提示语或文字
extension String {
    
    static var netConnectError: String {
        get {
            return "请检查您的网络"
        }
    }
    
    static var serviceResponseError: String {
        get {
            return "数据返回异常，请联系管理员"
        }
    }
    
    
    static var serviceWaiteOpen: String {
        get {
            return "功能暂未开放，敬请期待"
        }
    }
    
    static var reviewPlaceHolder: String {
        get {
            return "爱评论的人运气不会太差"
        }
    }
    
    
}
